#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# vim:tabstop=4
#
# Copyright (c) 2010 by xkhhdx
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys, os
default_encoding = 'utf-8'
import base64
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

import cgi
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import updaters
from configure import *

class handler_main(webapp.RequestHandler):
    def get(self):
        self.response.out.write("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><title>配置</title></head><body><ol>")

        self.response.out.write("请选择任务：")
        try:
            isfirst = configs["sinatid"]
        except Exception, e:
            configs["f5api"] = ""
            configs["stapi"] = ""
            configs["sinatid"] = ""
            configs["bitlyusername"] = ""
            configs["bitlyapikey"] = ""

            self.response.out.write("这是第一次设置，请配置：<br/>")

        try:
            aa = configs["bitlyusername"]
        except Exception, e:
            configs["bitlyusername"] = ""
            configs["bitlyapikey"] = ""
        try:
            aa = configs["twitterid"]
        except Exception, e:
            configs["twitterid"] =""

        self.response.out.write(
            "<form action='/config_first' method='post'>"
                "新浪微博 用户名或ID：<input name='sinatid' value='" + configs["sinatid"] + "'/><br/>"
                "Twitter 用户名或ID：<input name='twitterid' value='" + configs["twitterid"] + "'/><br/><br/>"
                "新浪微博 API-key：<input name='sinatapikey' value='" + configs["stapi"] + "'/><br/>"
                "Follow5  API-key：<input name='f5apikey' value='" + configs["f5api"] + "'/><br/>"
                "Bit.ly  用户名：<input name='bitlyusername' value='" + configs["bitlyusername"] + "'/><br/>"
                "Bit.ly  API-key：<input name='bitlyapikey' value='" + configs["bitlyapikey"] + "'/><br/>"
                "<div><input type='submit' value='保存'></div>"
            "</form>"
        )

        self.response.out.write("<li><a href='/config'>设置 同步网站</a></li>")
        self.response.out.write("<li></li>")

        self.response.out.write('</ol></body></html>')

class handler_first(webapp.RequestHandler):
    def post(self):
        configs["f5api"] = self.request.get('f5apikey')
        configs["stapi"] = self.request.get('sinatapikey')
        configs["sinatid"] = self.request.get('sinatid')
        configs["twitterid"] = self.request.get('twitterid')
        configs["bitlyusername"] = self.request.get('bitlyusername')
        configs["bitlyapikey"] = self.request.get('bitlyapikey')
        
        save_setting()
        self.redirect('/config')

    #def get(self):
        #self.response.out.write("请使用 POST 方法\n\tPOST 参数：\n\t\tserviceprovider: 服务提供商\n\t\tconfig: 配置")


class handler_config(webapp.RequestHandler):
    def get(self):
            #"<option value='%s'> %s </option>
        cc = handler_config_getconfig()
        template_values = {
            #'usermanages'    :    load_usermanage(),
            'updaters'       :    "\n".join(["<option value='" +x + "'>" +x+ "</option>" for x in updaters.microblogs]),
            'operation'      :    1,
            'desti'          :    [
	            { 
		            "id"               : base64.encodestring(str(x.create_time))[:-2], #x.key(),
		            "updaters"         : "\n".join([ "<option label='" + y + (y==x.serviceprovider and ["' selected = 'selected'"] or ["'"])[0]  + ">" + updaters.microblogs[y].__serviceprovider__ + "</option>"  for y in updaters.microblogs]),
		            "user"             : x.user,
		            "serviceprovider"  : x.serviceprovider,
		            "config"           : x.config,
		            "create_time"      : x.create_time,
		            "config_page"      : cc.get(x.serviceprovider,x.create_time,True)
	            } for x in load_usermanage()
            ],
            'tab'            :    1,

        }
        #import os
	    #for param in os.environ.keys():
	    #    self.response.out.write( "%20s %s<br/>" % (param,os.environ[param]))
        self.response.out.write(template.render(os.path.join('static', 'config.html'), template_values))

class handler_config_edit(webapp.RequestHandler):
    def get(self):
        template_values = {
            'usermanages'    :    load_usermanage(),
            'updaters'       :    "\n".join(["<option value='" +x + "'>" +x+ "</option>" for x in updaters.microblogs]),
            'operation'      :    2,
        }

        self.response.out.write(template.render("config.html", template_values))


class handler_config_addnew(webapp.RequestHandler):
    def post(self):
        usermanage = UserManages()

        if users.get_current_user():
            usermanage.user = users.get_current_user()

        usermanage.serviceprovider = self.request.get('serviceprovider')
        usermanage.config = self.request.get('config')
        usermanage.put()

        refresh_usermanage_cache()
        #self.response.out.write( "您提交的信息已经保存" )
        self.redirect('/config')

    #def get(self):
        #self.response.out.write("请使用 POST 方法\n\tPOST 参数：\n\t\tserviceprovider: 服务提供商\n\t\tconfig: 配置")

class handler_config_delete(webapp.RequestHandler):
    #def post(self):
        #self.response.out.write("请使用 GET 方法\n\tGET 参数：\n\t\ttimestamp: 时间戳记\n\t\tcomfirmed: 是否经过删除验证")

    def get(self):
        comfirmed  = self.request.get('comfirmed')
        item_time_stamp = self.request.get('timestamp')

        if not comfirmed == "true":
            self.response.out.write(u"""
            您确定要删除 %s 时注册的这个帐号么？<br>
            <a href="/config/desti/delete?comfirmed=true&timestamp=%s">是</a>\t<a href="/config">否</a>
            """ % ( item_time_stamp, item_time_stamp))

        else:

            self.response.out.write("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><meta http-equiv='Refresh' content='1;URL=/config/desti'/><title>deleting...</title></head><body>")
            self.response.out.write(item_time_stamp)

            msgs = db.GqlQuery("SELECT * FROM UserManages ORDER BY create_time")
            for msg in msgs:
                if item_time_stamp == str(msg.create_time):
                    msg.delete()
                    refresh_usermanage_cache()
                    self.response.out.write("<br/>这条记录已经删除！<br/>一秒之后自动跳转……<br/>")

            self.response.out.write('</body></html>')
            
#localhost:8080/config/getconfig?sp=renren&create_time=2010-08-24 02:06:18.650000

class handler_config_getconfig(webapp.RequestHandler):
    def get(self, serviceprovider = "", create_time = "", return_html = False):
        pro = None; ret = ""

        if not return_html:
            serviceprovider = self.request.get('sp')
            create_time = self.request.get('create_time')
        try:
            pro = eval("updaters." + serviceprovider + ".__properties__")
        except Exception:
            ret = "<!-- Unknown ServiceProvider! -->Unknown ServiceProvider! "
        else:
            if len(str(create_time)):
                for usermanage in load_usermanage():
                    #ret = ret + str(usermanage.create_time) + str(create_time)+ str()
                    if str(usermanage.create_time) == str(create_time):
                        current_configs = eval(usermanage.config)
                        for item in current_configs:
                        #<label>配置：</label>
                            ret = ret + "<label>" + pro[item] +"</label>" + "<input name='" + item + "' value='" + current_configs[item] + "'/><br/><br/>"
                            #<div class="accountControlButton">	<a class="changeRemoteKey" type="remotekey" href="/config/edit/%s"> 编辑 </a></div>
            else:
                for item in pro:
                    #<label>配置：</label>
                    ret = ret + "<label>" + pro[item] +"</label>" + "<input name='" + item + "' value='请在这里填写" + pro[item] + "'/><br/><br/>"
                    
        if (return_html):
            return ret
            
        self.response.out.write(ret)

    #def post(self):
        #self.response.out.write("请使用 GET 方法\n\tGET 参数：\n\t\tsp: 服务提供商")

class handler_cache_refresh(webapp.RequestHandler):
    def get(self):
        reload_all()

class handler_error(webapp.RequestHandler):
    def post(self):
    	
        self.response.out.write("404 not found!")
    def get(self):
    	
        self.response.out.write("404 not found!")

application = webapp.WSGIApplication([
    ('/', handler_main),
    ('/config_first/?', handler_first),
    ('/config/desti/?', handler_config),
    ('/config/desti/addnew/?', handler_config_addnew),
    ('/config/desti/delete/?', handler_config_delete),
    ('/config/desti/edit/?', handler_config_edit),
    ('/config/getconfig', handler_config_getconfig),
    ('/config/.*', handler_error),
    ('/cache/refresh', handler_cache_refresh),
], debug=True)

def main():
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

